import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:interactive_chart/interactive_chart.dart';

class StockList {
  late int timestamp;
  late double open;
  late double high;
  late double low;
  late double close;
  late double volume;

  static StockList? fromMap(Map<String, dynamic> map) {
    if (map == null) return null;
    StockList stockListBean = StockList();
    stockListBean.timestamp = map['timestamp'];
    stockListBean.open = map['open'];
    stockListBean.high = map['high'];
    stockListBean.low = map['low'];
    stockListBean.close = map['close'];
    stockListBean.volume = map['volume'];
    return stockListBean;
  }

  Map toJson() => {
    "timestamp": timestamp,
    "open": open,
    "high": high,
    "low": low,
    "close": close,
    "volume": volume,
  };

}

class TestStock extends StatefulWidget {
  @override
  _TestStockState createState() => _TestStockState();
}

class _TestStockState extends State<TestStock> {

  late List<CandleData> _data = [];
  bool _darkMode = true;
  bool _showAverage = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getData();
  }

  void _getData()async{
    var result = await new Dio().get("http://192.168.1.104:18063/api/get/stock/all");

    List<StockList?> list = (result.data as List<dynamic>)
        .map((e) => StockList.fromMap((e as Map<String, dynamic>)))
        .toList();


    List<CandleData> _data1 = list
        .map((row) => CandleData(
      timestamp: row!.timestamp * 1000,
      open: row.open.toDouble(),
      high: row.high.toDouble(),
      low: row.low.toDouble(),
      close: row.close.toDouble(),
      volume: row.volume.toDouble(),
    ))
        .toList();

    setState(() {
      _data = _data1;
    });

  }
//16.37
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        brightness: _darkMode ? Brightness.dark : Brightness.light,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text("Interactive Chart Demo"),
          centerTitle: true,
          actions: [
            IconButton(
              icon: Icon(_darkMode ? Icons.dark_mode : Icons.light_mode),
              onPressed: () => setState(() => _darkMode = !_darkMode),
            ),
            IconButton(
              icon: Icon(
                _showAverage ? Icons.show_chart : Icons.bar_chart_outlined,
              ),
              onPressed: () {
                setState(() => _showAverage = !_showAverage);
                if (_showAverage) {
                  _computeTrendLines();
                } else {
                  _removeTrendLines();
                }
              },
            ),
          ],
        ),
        body: SafeArea(
          minimum: const EdgeInsets.all(24.0),
          child: _data.length > 5? InteractiveChart(
            /** Only [candles] is required */
            candles: _data,
            /** Uncomment the following for examples on optional parameters */

            /** Example styling */
            style: ChartStyle(
              priceGainColor: Colors.red,
              priceLossColor: Colors.green,
              volumeColor: Colors.white70,
              trendLineStyles: [
                Paint()
                  ..strokeWidth = 1.0
                  ..strokeCap = StrokeCap.round
                  ..color = Colors.deepOrange,
                Paint()
                  ..strokeWidth = 1.0
                  ..strokeCap = StrokeCap.round
                  ..color = Colors.orange,
                Paint()
                  ..strokeWidth = 1.0
                  ..strokeCap = StrokeCap.round
                  ..color = Colors.green,
                Paint()
                  ..strokeWidth = 1.0
                  ..strokeCap = StrokeCap.round
                  ..color = Colors.teal,
              ],
              priceGridLineColor: Color.fromRGBO(255, 255, 255, 0.2),
              priceLabelStyle: TextStyle(color: Colors.red),
              timeLabelStyle: TextStyle(color: Colors.black54),
              selectionHighlightColor: Colors.red.withOpacity(0.2),
              overlayBackgroundColor: Colors.red[900]!.withOpacity(0.6),
              overlayTextStyle: TextStyle(color: Colors.red[100]),
              timeLabelHeight: 32,
              volumeHeightFactor: 0.2, // volume area is 20% of total height
            ),
            /** Customize axis labels */
             //timeLabel: (timestamp, visibleDataCount) => "📅",
             //timeLabel: (timestamp, visibleDataCount) => ""+"时间"+"",
             //priceLabel: (price) => "${price.round()} 💎",
            /** Customize overlay (tap and hold to see it)
             ** Or return an empty object to disable overlay info. */
            overlayInfo: (candle) => {
              "💎": "🤚    ",
              "最高价": "${candle.high?.toStringAsFixed(2)}",
              "最低价": "${candle.low?.toStringAsFixed(2)}",
              "开盘价": "${candle.open?.toStringAsFixed(2)}",
            },
            /** Callbacks */
            onTap: (candle) => print(candle.open),
            onCandleResize: (width) => print("each candle is $width wide"),
          ):Text(""),
        ),
      ),
    );
  }

  _computeTrendLines() {
    final ma7 = CandleData.computeMA(_data, 7);
    final ma20 = CandleData.computeMA(_data, 20);
    final ma30 = CandleData.computeMA(_data, 30);
    final ma120 = CandleData.computeMA(_data, 120);

    for (int i = 0; i < _data.length; i++) {
      _data[i].trends = [ma7[i], ma20[i], ma30[i],ma120[i]];
    }
  }

  _removeTrendLines() {
    for (final data in _data) {
      data.trends = [];
    }
  }
}